package com.smooware.icms.service;

import java.util.ArrayList;
import java.util.List;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.smooware.icms.InControllApp;
import com.smooware.icms.fragment.sync.AuthorizationFragment;

public class ICMSAuthorizationService extends Service {

	private static final String TAG = ICMSAuthorizationService.class.getSimpleName();

	private AuthorizationServiceBinderImpl binderImpl;

	@Override
	public void onCreate() {
		super.onCreate();

		binderImpl = new AuthorizationServiceBinderImpl();

		startSynchronization();
	}

	@Override
	public IBinder onBind(final Intent intent) {
		return binderImpl;
	}

	/**
	 * Starts synchronization process. If synchronization process is once
	 * started service will be kept running until this process is fully
	 * completed.
	 */
	private void startSynchronization() {
		Log.d(TAG, "Synchronization ");
	}

	/**
	 * Starts authorization process.
	 */
	private void startAuthorization() {
		Log.d(TAG, "Authorization");

		InControllApp application = (InControllApp) getApplicationContext();

		application.getICMSSecurityManager().setAuthorizedTrue();
		application.getICMSSecurityManager().setTrustedAccessTrue();

		completeAuthorization();
	}

	/**
	 * Completes authorization process.
	 */
	private void completeAuthorization() {
		binderImpl.notifyAuthorizationComplete();
	}

	/**
	 * Forces keeping service alive even if all view are already unbounded.
	 */
	private void keepAlive() {
		startService(new Intent(this, ICMSAuthorizationService.class));
	}

	/**
	 * Implementation of {@link AuthorizationServiceBinder} interface. Used to
	 * process comunication between service and UI modules.
	 * 
	 * @author Orest Vovchak
	 * 
	 */
	private class AuthorizationServiceBinderImpl extends Binder implements
			AuthorizationServiceBinder {

		private final List<AuthorizationFragment> observers = new ArrayList<AuthorizationFragment>();

		@Override
		public boolean isSynchronizationComplete() {
			return false;
		}

		@Override
		public void registerFragmentObserver(
				final AuthorizationFragment fragment) {
			observers.add(fragment);
		}

		@Override
		public void unregisterFragmentObserver(
				final AuthorizationFragment fragment) {
			observers.remove(fragment);

			if (observers.isEmpty() && !isSynchronizationComplete()) {
				keepAlive();
			}
		}

		@Override
		public void startAuthorizationProcess() {
			startAuthorization();
		}

		/**
		 * Notifies {@link AuthorizationFragment} observers that authorization
		 * process in service is completed. Stops service.
		 */
		public void notifyAuthorizationComplete() {
			for (AuthorizationFragment fragment : observers) {
				fragment.notifyServiceCompletion();
			}

			observers.clear();

			stopSelf();
		}
	}
}
